<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增部位"
    width="900px"
    @close="closeDialog"
  >
    <el-form class="aceauForm" label-width="120px" :model="state.form">
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="部位编码" required>
            <el-input v-model="state.form.partCode" placeholder="请填写编码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部位名称">
            <el-input v-model="state.form.partName" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备编码">
            <el-input
              v-model="state.form.equipCode"
              placeholder=""
              @click="toSelectEquip"
              @focus="toSelectEquip"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称">
            <el-input v-model="state.form.equipName" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号">
            <el-input v-model="state.form.equipSpec" disabled placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model="state.form.remark" placeholder="备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <equipPick ref="equipPickRef" @success-callback="pickEquipCallback" />
</template>

<script setup>
  import equipPick from '@/plugins/equipPick'
  import { addRepairPartApi } from '@/api/equip/equip_api'

  const $baseLoading = inject('$baseLoading')
  const $baseMessage = inject('$baseMessage')

  const dialogVisible = ref(false)

  const state = reactive({
    form: {},
  })

  const equipPickRef = ref()

  const openDialog = () => {
    dialogVisible.value = true
  }

  const toSelectEquip = () => {
    equipPickRef.value.openDialog()
  }

  const pickEquipCallback = (value) => {
    state.form.pkEqlist = value.pkEqlist
    state.form.equipCode = value.equipCode
    state.form.equipName = value.equipName
  }

  const save = async () => {
    const load = $baseLoading()
    try {
      const { code, msg } = await addRepairPartApi(state.form)
      if (code === 2000) {
        $baseMessage(msg, 'success')
        dialogVisible.value = false
        _emit('success-callback')
      } else {
        $baseMessage(msg, 'error')
      }
    } finally {
      load.close()
    }
  }

  defineExpose({ openDialog })
  const _emit = defineEmits(['success-callback'])
</script>
